package ru.amse.vlassiev.view;

import javax.swing.*;
import ru.amse.vlassiev.model.*;
import java.awt.event.*;
import java.io.*;

public class RefreshFiltersButton extends JButton {

	private class RefreshMouseListener implements MouseListener {

		private final IFiltrator myFiltrator;
		private final File myFile;
		private final MainWindow myMainWindow;
		
		public RefreshMouseListener(IFiltrator filtrator, File file, MainWindow mainWindow) {
			myFiltrator = filtrator;
			myFile = file;
			myMainWindow = mainWindow;
		}
		
		public void mouseClicked(MouseEvent arg0) {
			try {
				FileReader reader = new FileReader(myFile);
				int c = reader.read();
				myFiltrator.removeAllFilters();
				while (c != -1) {
					StringBuilder condition = new StringBuilder();
					do {
						if (Character.isLetterOrDigit(c)) {
							condition.append((char) c);
						}
						c = reader.read();
					} while (c != -1 && !Character.isWhitespace(c));
					if (condition.length() > 0) {
//System.err.println("DEBUG: condition = [" + condition.toString() + "]");
						IView view = new Graph(condition.toString());
						myMainWindow.addView((JPanel) view);
						myFiltrator.addFilter(new Filter(condition.toString(), 1, view));
					}
				}
			} catch (IOException e) {
				
			} 
		}

		public void mouseEntered(MouseEvent arg0) {
		}

		public void mouseExited(MouseEvent arg0) {
		}

		public void mousePressed(MouseEvent arg0) {
		}

		public void mouseReleased(MouseEvent arg0) {
		}

	}
	
	public RefreshFiltersButton(IFiltrator filtrator, MainWindow mainWindow) {
		super("Refresh filters");
		this.addMouseListener(new RefreshMouseListener(filtrator, new File("filters.sl"), mainWindow));
	}
	

}
